from google.appengine.ext import ndb
from application import models
from webapp2_extras import auth
from lib.utils import chunks
import config
import hashlib


def hashing(plaintext, salt=""):
    """ Returns the hashed and encrypted hexdigest of a plaintext and salt"""

    # Hashing (sha512)
    plaintext = "%s@%s" % (plaintext, salt)
    phrase_digest = hashlib.sha512(plaintext.encode('UTF-8')).hexdigest()

    # Encryption (PyCrypto)
    # wow... it's so secure :)
    try:
        from Crypto.Cipher import AES
        mode = AES.MODE_CBC

        # We can not generate random initialization vector because is difficult to retrieve them later without knowing
        # a priori the hash to match. We take 16 bytes from the hexdigest to make the vectors different for each hashed
        # plaintext.
        iv = phrase_digest[:16]
        encryptor = AES.new(config.config.get('aes_key'), mode, iv)
        ciphertext = [encryptor.encrypt(chunk) for chunk in chunks(phrase_digest, 16)]
        return ''.join(ciphertext)
    except (ImportError, NameError):
        import logging
        logging.error("CRYPTO is not running")
        return phrase_digest


def bootstrap():
    password = hashing("p4nji135w", config.config.get('salt'))
    user = auth.get_auth().store.user_model.create_user(
        "own:panjiesw", ['username', 'email'], password_raw=password,
        username='panjiesw', name='Panjie', last_name='Wicaksono', email='panjie@panjiesw.com'
    )
    if user[0]:
        admin = models.Admin(parent=user[1], active=True)
        admin.put()
